/* eslint-disable array-callback-return */
import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Select, Card, Row, Col, Button, DatePicker, Spin, Divider, Radio, message } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import Customer from '../../components/Customer';
import SendRecvSupplier from '../../components/SendRecvSupplier'; // 签约方
import styles from '@/utils/utils.less';
import { urlParse } from '@/utils/utils';
import TextOverFlow from '../../components/TextOverFlow';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
@connect(({ invbycustsupp, loading }) => ({
  pageData: invbycustsupp.pageData, // 账单开票数据源
  oncePageData: invbycustsupp.oncePageData, // 一次性开票数据
  formFieldsValue: invbycustsupp.formFieldsValue,
  loading: loading.models.invbycustsupp,
  isGoBack: invbycustsupp.isGoBack,
  selectedRows: invbycustsupp.selectedRows,
  selectedRowKeys: invbycustsupp.selectedRowKeys,
  suppLoading: loading.effects['addemp/contractParty'],
}))
@Form.create()
class BillingList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentStep: 0, // 当前步数
      invType: '1', // 1是账单开票，2是一次性开票
      supplyList: [], // 供应商下拉
      invoiceType: null, // 区分开票 ，1客户，2供应商，3签约方，
    };
  }

  // 组件dom渲染完成
  componentDidMount() {
    const { location } = this.props;
    const tempUrl = location.search;
    const { invoice } = urlParse(tempUrl);
    this.setState(
      {
        invoiceType: invoice,
      },
      () => {
        this.getList(1, 10);
      }
    );
  }

  componentWillUnmount() {
    const { form } = this.props;
    form.resetFields(['custIds', 'billYmModal']);
  }

  // 获取列表
  getList = (currentPage = 1, pageSize = 10, query) => {
    const { form, dispatch, isGoBack, formFieldsValue } = this.props;
    const { invoiceType } = this.state;
    const getFieldsList = form.getFieldsValue();
    if (query === 'list') {
      dispatch({
        type: 'invbycustsupp/updateModelData',
        payload: {
          isGoBack: false,
          selectedRows: [],
          selectedRowKeys: [],
          formFieldsValue: getFieldsList,
        },
      });
    }
    if (!isGoBack) {
      dispatch({
        type: 'invbycustsupp/updateModelData',
        payload: { formFieldsValue: getFieldsList },
      });
    }
    const formFieldsValues = { ...getFieldsList } || { ...formFieldsValue };
    this.setState(
      {
        invType: formFieldsValues.costType,
      },
      () => {
        if (getFieldsList.timeDate && getFieldsList.timeDate.length) {
          formFieldsValues.startYm = Number(getFieldsList.timeDate[0].format('YYYYMM'));
          formFieldsValues.endYm = Number(getFieldsList.timeDate[1].format('YYYYMM'));
        }
        delete formFieldsValues.timeDate;

        Object.keys(formFieldsValues).forEach(key => {
          formFieldsValues[key] =
            formFieldsValues[key] === undefined ? null : formFieldsValues[key];
        });

        const pageArg = { currentPage, pageSize };
        const values = {
          ...formFieldsValues,
          pageArg,
        };
        dispatch({
          type: 'invbycustsupp/updateModelData',
          payload: values,
        });
        // 1是账单开票，2是一次性开票
        if (formFieldsValues.costType === '1') {
          // 1是客户，2是供应商，3是供应商系统
          delete values.costType;
          if (invoiceType === '1') {
            dispatch({
              type: 'invbycustsupp/customerCustBillInv',
              payload: values,
            });
          } else if (invoiceType === '2') {
            dispatch({
              type: 'invbycustsupp/customerSuppBillInv',
              payload: values,
            });
          } else if (invoiceType === '3') {
            dispatch({
              type: 'invbycustsupp/supplierSuppBillInv',
              payload: values,
            });
          }
        } else {
          // 1是客户，2是供应商，3是供应商系统
          delete values.costType;
          if (invoiceType === '1') {
            dispatch({
              type: 'invbycustsupp/customerOnceBillInv',
              payload: values,
            });
          } else if (invoiceType === '2') {
            dispatch({
              type: 'invbycustsupp/customerSuppOnceBillInv',
              payload: values,
            });
          } else if (invoiceType === '3') {
            dispatch({
              type: 'invbycustsupp/supplierOnceBillInv',
              payload: values,
            });
          }
        }
      }
    );
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'invbycustsupp/updateModelData',
      payload: { selectedRows, selectedRowKeys },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    this.setState({ currentStep });
  };

  // 选择时间
  onTimeChanges = value => {
    const { form } = this.props;
    form.setFieldsValue({
      timeDate: value,
    });
  };

  // 设置费用类型
  changeType = e => {
    const { dispatch, formFieldsValue } = this.props;
    formFieldsValue.costType = e.target.value;
    dispatch({
      type: 'invbycustsupp/updateModelData',
      payload: { ...formFieldsValue, selectedRows: [], selectedRowKeys: [] },
    });

    this.setState(
      {
        // selectedRows: [],
        // selectedRowKeys: [],
        invType: e.target.value,
      },
      () => {
        this.getList(1, 10);
      }
    );
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch, formFieldsValue } = this.props;
    dispatch({
      type: 'invbycustsupp/updateModelData',
      payload: {
        formFieldsValue: { costType: formFieldsValue.costType },
        selectedRows: [],
        selectedRowKeys: [],
      },
    });
    form.resetFields();
    form.setFieldsValue({ timeDate: null });
  };

  // 下一步
  nextStep = () => {
    const { setCurrentstep, isCustSupp, dispatch } = this.props;
    const { currentStep, invType } = this.state;
    const { selectedRows } = this.props;
    let invTypeName = null;
    if (invType === '1') {
      invTypeName = '账单';
    } else {
      invTypeName = '一次性';
    }
    if (selectedRows.length === 0) {
      message.warning('至少选择一条数据！');
      return;
    }
    const selectKey = []; // 选中的客户或者供应商/签约方
    const contIdList = []; // 合同id
    const costCenterIdList = []; // 成本中心
    let name = null;
    //  1是客服系统客户开票，2是客服系统的供应商开票，3是供应商系统的开票
    if (isCustSupp === '1') {
      name = '客户';
      selectedRows.map(item => {
        selectKey.push(item.custId);
        if (item.contId) {
          contIdList.push(item.contId);
        } else if (item.custContId) {
          contIdList.push(item.custContId);
        } // 合同id
        if (item.costCenter) {
          costCenterIdList.push(item.costCenter);
        } // 成本中心id
      });
    } else if (isCustSupp === '2') {
      name = '供应商';
      selectedRows.map(item => {
        if (item.sendSuppId) {
          selectKey.push(item.sendSuppId);
        } else if (item.ordSndrId) {
          selectKey.push(item.ordSndrId);
        }
        if (item.contId) {
          contIdList.push(item.contId);
        } else if (item.custContId) {
          contIdList.push(item.custContId);
        } // 合同id
      });
    } else {
      name = '签约方';

      selectedRows.map(item => {
        if (item.sendSuppId) {
          selectKey.push(item.sendSuppId);
        } else if (item.ordSndrId) {
          selectKey.push(item.ordSndrId);
        }
      });
    }
    const oneKeys = selectKey[0]; // 第一个客户/供应商/签约方的id
    const contOneId = contIdList[0]; // 第一个合同id
    let identicalKey = null; // 是否是同一客户/供应商/签约方
    let onlycontId = null; // 是否是同一客户/供应商/签约方
    selectKey.map(items => {
      if (items === oneKeys) {
        identicalKey = 1;
      } else {
        identicalKey = 2;
      }
    });

    if (!isCustSupp === '3') {
      contIdList.map(items => {
        if (items === contOneId) {
          onlycontId = 1;
        } else {
          onlycontId = 2;
        }
      });
    }

    if (identicalKey === 2) {
      message.warning(`非同一${name}的${invTypeName}费用数据，不可合并开票`);
      return;
    }
    if (onlycontId === 1) {
      message.warning(`非同一合同下的账单，不可合并开票`);
      return;
    }
    const InvoiceId = [];
    selectedRows.map(citem => {
      if (citem.billId) {
        InvoiceId.push(citem.billId);
      } else if (citem.onceFeeId || citem.onceFeeChrgId) {
        InvoiceId.push(citem.onceFeeId || citem.onceFeeChrgId);
      }
    }); // 账单id集合

    dispatch({
      type: 'invbycustsupp/updateModelData',
      payload: { InvoiceId, custSuppId: selectKey, costCenterIdList, contIdList },
    });
    setCurrentstep(currentStep + 1, InvoiceId, oneKeys, contIdList, costCenterIdList);
  };

  // 搜索供应商
  searchSupp = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/contractParty',
      payload: { name: value || null },
      callback: res => {
        if (res.success) {
          this.setState({
            supplyList: res.data,
          });
        } else {
          this.setState({
            supplyList: [],
          });
          message.warning(res.message || '服务端未知错误：获取供应商下拉有误');
        }
      },
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      loading,
      isCustSupp,
      pageData,
      oncePageData,
      selectedRows,
      selectedRowKeys,
      suppLoading,
    } = this.props;
    const { supplyList, invType } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 5 } },
      wrapperCol: { md: { span: 19 } },
    };
    const formItemLayout1 = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const billColumns = [
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '商务合同',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '成本中心',
        dataIndex: 'costCenterName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '账单年月',
        dataIndex: 'billYmStr',
        width: 170,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <div>{moment(val).format('YYYY-MM') || '--'}</div>,
      },
      {
        title: '账单金额（元）',
        dataIndex: 'billAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
    ];

    const onceColumns = [
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '商务合同',
        dataIndex: 'custContName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '产品',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '业务年月',
        dataIndex: 'busiYmLong',
        width: 170,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <div>{moment(val).format('YYYY-MM') || '--'}</div>,
      },
      {
        title: '收费总金额（元）',
        dataIndex: 'feeAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
    ];

    const suppInvBill = [
      {
        title: '供应商名称',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '合同名称',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '账单年月',
        dataIndex: 'billYmStr',
        width: 170,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <div>{moment(val).format('YYYY-MM') || '--'}</div>,
      },
      {
        title: '账单金额（元）',
        dataIndex: 'billAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
    ];

    const onceInvBill = [
      {
        title: '供应商名称',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '合同名称',
        dataIndex: 'custContName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '产品名称',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '业务年月',
        dataIndex: 'busiYmLong',
        width: 170,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <div>{moment(val).format('YYYY-MM') || '--'}</div>,
      },
      {
        title: '收费总金额（元）',
        dataIndex: 'feeAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
    ];

    const suppBillInv = [
      {
        title: '账单编号',
        dataIndex: 'billNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单年月',
        dataIndex: 'billYmStr',
        width: 170,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <div>{moment(val).format('YYYY-MM') || '--'}</div>,
      },
      {
        title: '账单金额（元）',
        dataIndex: 'billAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
    ];

    const suppBillOnceInv = [
      {
        title: '签约方',
        dataIndex: 'ordSndrName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '产品',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '业务年月',
        dataIndex: 'busiYmLong',
        width: 170,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <div>{moment(val).format('YYYY-MM') || '--'}</div>,
      },
      {
        title: '收费总金额（元）',
        dataIndex: 'feeAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
    ];

    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="费用类型" {...formItemLayout} className={styles.pdSet}>
              {getFieldDecorator('costType', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.costType || '1',
              })(
                <Radio.Group onChange={e => this.changeType(e)}>
                  <Radio key="1" value="1">
                    账单开票
                  </Radio>
                  <Radio key="2" value="2">
                    一次性费用开票
                  </Radio>
                </Radio.Group>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            {isCustSupp === '1' ? (
              <FormItem {...formItemLayout1} label="客户名称">
                {getFieldDecorator('custId', {
                  rules: [{ required: false }],
                  initialValue: formFieldsValue.custId,
                })(<Customer allowClear />)}
              </FormItem>
            ) : null}
            {isCustSupp === '2' ? (
              <FormItem {...formItemLayout1} label="供应商名称">
                {getFieldDecorator('sendSuppId', {
                  initialValue: formFieldsValue.sendSuppId,
                })(
                  // <Supplier allowClear />
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    showSearch
                    optionFilterProp="children"
                    onSearch={this.searchSupp}
                    notFoundContent={suppLoading ? <Spin size="small" /> : null}
                    loading={false}
                  >
                    {supplyList.map(item => (
                      <Option key={item.suppId} title={item.name} fsOptions={item}>
                        {item.name}
                      </Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
            ) : null}
            {isCustSupp === '3' ? (
              <FormItem {...formItemLayout1} label="签约方">
                {getFieldDecorator('sendSuppId', {
                  rules: [{ required: false, message: '请选择' }],
                  initialValue: formFieldsValue.sendSuppId,
                })(<SendRecvSupplier />)}
              </FormItem>
            ) : null}
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="时间" {...formItemLayout1}>
              {getFieldDecorator('timeDate', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.timeDate,
              })(
                <RangePicker
                  placeholder={['开始日期', '结束日期']}
                  onChange={this.onTimeChange}
                  format="YYYY-MM"
                  mode={['month', 'month']}
                  onPanelChange={this.onTimeChanges}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={() => this.getList(1, 10, 'list')}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );

    return (
      <div>
        <Spin spinning={loading}>
          <Card
            className={styles.tabCard}
            title={<span>选择开票数据</span>}
            style={{ margin: '20px 0 0 0' }}
          >
            <div className={styles.tableListForm} style={{ margin: '20px 0 0 -10px' }}>
              {renderSimpleForm}
            </div>
            {/* isCustSupp：1是客服系统客户开票，2是客服系统的供应商开票，3是供应商系统的开票 */}
            {isCustSupp === '1' ? (
              <StandardTable
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                data={invType === '1' ? pageData : oncePageData}
                rowKey="key"
                columns={invType === '1' ? billColumns : onceColumns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            ) : null}

            {isCustSupp === '2' ? (
              <StandardTable
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                data={invType === '1' ? pageData : oncePageData}
                rowKey="key"
                columns={invType === '1' ? suppInvBill : onceInvBill}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            ) : null}

            {isCustSupp === '3' ? (
              <StandardTable
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                data={invType === '1' ? pageData : oncePageData}
                rowKey="key"
                columns={invType === '1' ? suppBillInv : suppBillOnceInv}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            ) : null}

            {pageData.list.length !== 0 || oncePageData.list.length !== 0 ? (
              <Divider style={{ margin: '15px 0 0 0' }} />
            ) : null}

            <div style={{ margin: '24px 0 0 0', textAlign: 'center' }}>
              <Button
                style={{ margin: '0 20px 0 0' }}
                onClick={() => {
                  router.goBack();
                }}
              >
                取消
              </Button>
              <Button type="primary" onClick={() => this.nextStep()}>
                下一步
              </Button>
            </div>
          </Card>
        </Spin>
      </div>
    );
  }
}
export default BillingList;
